// components/richtext/richtext.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    formats: {},
    img: '',
    bottom: 0,
    readOnly: false,
    placeholder: '请输入...',
    _focus: false,
  },

  /**
   * 组件的方法列表
   */
  methods: {
    readOnlyChange() {
      this.setData({
        readOnly: !this.data.readOnly
      })
    },
    onLoad() {
      this.initValidate()
    },
    // 编辑器初始化完成时触发
    onEditorReady() {
      const that = this;
      wx.createSelectorQuery().select('#editor').context(function (res) {
        that.editorCtx = res.context;
      }).exec();
    },
    undo() {
      this.editorCtx.undo();
    },
    redo() {
      this.editorCtx.redo();
    },
    format(e) {
      let {
        name,
        value
      } = e.target.dataset;
      if (!name) return;
      // console.log('format', name, value)
      this.editorCtx.format(name, value);
    },
    // 通过 Context 方法改变编辑器内样式时触发，返回选区已设置的样式
    onStatusChange(e) {
      const formats = e.detail;
      this.setData({
        formats
      });
    },
    // 插入分割线
    insertDivider() {
      this.editorCtx.insertDivider({
        success: function () {
          console.log('insert divider success')
        }
      });
    },
    // 清除
    clear() {
      this.editorCtx.clear({
        success: function (res) {
          console.log("clear success")
        }
      });
    },
    // 移除样式
    removeFormat() {
      this.editorCtx.removeFormat();
    },
    // 插入当前日期
    insertDate() {
      const date = new Date()
      const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
      this.editorCtx.insertText({
        text: formatDate
      });
    },
    //图片上传
    insertImage() {
      const that = this
      wx.chooseImage({
        count: 1,
        success: function (res) {
          var temp = res.tempFilePaths[0];
          wx.uploadFile({
            url: 'https://tms.sds.com.cn:8300/hw/upload/files',
            filePath: temp,
            name: 'file',
            header: {
              'Content-Type': 'multipart/form-data',
            },
            formData: {
              method: 'POST',
              token: wx.getStorageSync('token'),
              sortVal: 1,
              updFileModule: 'business_wire',
              updFileType: 'pic',
            },
            success(res2) {
              var ress = JSON.parse(res2.data)
              if (ress.status == 100) {
                that.data.img = ress.data.updUrl
              }
              that.editorCtx.insertImage({
                src: that.data.img,
                data: {
                  id: 'abcd',
                  role: 'god'
                },
                width: '80%',
                success: function () {
                  console.log('insert image success')
                }
              })
            }
          })
        }
      })
    },
  }
})
